package com.joker.kehu;

import com.alibaba.fastjson.JSON;
import com.joker.pojo.SendNetty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;

public class MyClientHandler extends ChannelInboundHandlerAdapter {
    private SendNetty sendNetty;

    public MyClientHandler(SendNetty sendNetty) {
        this.sendNetty = sendNetty;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String s = JSON.toJSONString(sendNetty);
//        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
//        //发送消息到服务端
//        ctx.writeAndFlush(bytes);

        ctx.writeAndFlush(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接收服务端发送过来的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到服务端" + ctx.channel().remoteAddress() + "的消息：" + byteBuf.toString(CharsetUtil.UTF_8));
    }
}